require(['./config'],() =>{
    require(['url','template','header','footer','bootstrap','fly','cookie'],(url,template,header) =>{
        class ShopList {
            constructor () {
                this.rendonShopList().then(() =>{
                    this.goBack()
                    this.addcars()
                    this.reduce()
                    this.add()
                    this.wrapappera()
                    this.changePic()
                    this.appear()
                    this.buyNow()
                })
            }
            rendonShopList () {
                const id = location.search.slice(4)
                return new Promise((resolve,reject) =>{
                    if(id>1000){
                        $.get(`${url.xmyxDetail}`,{id},resp =>{
                            this.resp = resp
                            if(resp.code === 200){
                                var {
                                    id,
                                    photo,
                                    title,
                                    price,
                                    commodityHint,
                                    image,
                                    coupon,
                                    descContentList,
                                    accessoryHints
                                } = resp.data.detail
                                this.detail = {
                                    id,
                                    photo : photo.slice(0,4),
                                    title,
                                    price,
                                    commodityHint,
                                    coupon,
                                    image,
                                    descContentList : descContentList.filter((item) => item.image).slice(0,10),
                                    accessoryHints
                                }
                                $('#shop-detail').html(template('shop-detail-template',{...this.detail}))
                                resolve()
                            }else{
                                reject()
                            }
                        })
                    }else{
                        $.get('https://mshop.duoyi.com/api/product/detail/',{id},resp =>{
                            this.resp = resp
                            let {
                                id,
                                mobile_banner_imgs,
                                mobile_cover_img,
                                product_name,
                                product_description,
                                product_price
                            } = resp.data.product
                            let photo = mobile_banner_imgs,
                                title = product_name,
                                price = product_price,
                                image = mobile_cover_img
                            this.product = {
                                id,
                                photo,
                                image,
                                title,
                                product_description,
                                price
                            }
                            $('#shop-detail').html(template('shop-product-template',{...this.product}))
                            resolve()
                        })
                    }
                }) 
            }
            goBack () {
                $('.crumbs a').on('click',() =>{
                    window.history.go(-1)
                })
            }
            buyNow () {
                $('#buy-now').on('click',() =>{
                    if(this.detail){
                        location.href = `/html/submitOrder.html?id=${this.detail.id}`
                    }else{
                        location.href = `/html/submitOrder.html?id=${this.product.id}`
                    }
                })
            }
            addcars () {
                if(this.detail){
                    $('#add-car').on('click',(e) =>{
                        this.fly(e)
                        const username = $.cookie('username')
                        let  cart = localStorage.getItem('cart')
                        if(cart){
                            // 有数据
                            cart = JSON.parse(cart)
                            var isExist = cart.some((shop) =>{
                                return shop.id === this.detail.id
                            })
                            if(isExist){
                                cart = cart.map(shop =>{
                                    if(shop.id === this.detail.id){
                                        shop.count += Number($('.detail-commodity-num').val())
                                    }
                                    return shop
                                })
                            }else{
                                cart.push({
                                    ...this.detail,check : true,
                                    count:Number($('.detail-commodity-num').val())
                                })
                            }
                            localStorage.setItem('cart',JSON.stringify(cart))
                            
                        }else{
                            //没有数据
                            localStorage.setItem('cart',JSON.stringify([{
                                ...this.detail,check : true,
                                count:Number($('.detail-commodity-num').val())
                            }]))
                        }
                    })
                }else{
                    $('#add-car').on('click',(e) =>{
                        this.fly(e)
                        let  cart = localStorage.getItem('cart')
                        if(cart){
                            // 有数据
                            cart = Array.from(JSON.parse(cart))
                            var isExist = cart.some((shop) =>{
                                return shop.id === this.product.id
                            })
                            if(isExist){
                                cart = cart.map(shop =>{
                                    if(shop.id === this.product.id){
                                        shop.count += Number($('.detail-commodity-num').val())
                                    }
                                    return shop
                                })
                            }else{
                                cart.push({
                                    ...this.product,check : true,
                                    count:Number($('.detail-commodity-num').val())
                                })
                            }
                            localStorage.setItem('cart',JSON.stringify(cart))
                            
                        }else{
                            //没有数据
                            localStorage.setItem('cart',JSON.stringify([{
                                ...this.product,check : true,
                                count:Number($('.detail-commodity-num').val())
                            }]))
                        }
                    })
                }
            }
            reduce () {
                $('.option-num-reduce').on('click',() =>{
                   var num =  $('.detail-commodity-num').val()
                   num--
                   if(num<1){
                       num = 1
                       alert('亲，不能再少了')
                   }
                   $('.detail-commodity-num').val(num)
                   
                })
            }
            add () {
                $('.option-num-add').on('click',() =>{
                    var num =  $('.detail-commodity-num').val()
                    num++
                    if(num > 99){
                        num = 99
                        alert('亲，最多限购99件哦')
                    }
                    $('.detail-commodity-num').val(num)
                })
            }

            zoom (left,top) {
                if(left<0) left = 0
                if(top<0) top = 0
                if(left>$('.small-box').width()-$('.small-box').find('span').width()) 
                    left = $('.small-box').width()-$('.small-box').find('span').width()
                
                if(top>$('.small-box').height()-$('.small-box').find('span').height()) 
                    top = $('.small-box').height()-$('.small-box').find('span').height()

                var imgmaxleft =  $('.big-box').find('img').width()-$('.big-box').width()
                var spanmaxleft = $('.small-box').width()-$('.small-box').find('span').width()
                var imgmaxtop =  $('.big-box').find('img').height()-$('.big-box').height()
                var spanmaxtop = $('.small-box').height()-$('.small-box').find('span').height()
                var imgleft = left*imgmaxleft/spanmaxleft
                var imgtop = top*imgmaxtop/spanmaxtop
                
                $('.small-box').find('span').css('left',left+'px')
                $('.small-box').find('span').css('top',top+'px')
                $('.big-box').find('img').css('left',-imgleft+'px')
                $('.big-box').find('img').css('top',-imgtop+'px')
            }
            move () {
                const _this = this
                $('.small-box').on('mousemove',function (e){
                    let disx = e.clientX,
                        disy = e.clientY
                    var left = disx - $('.small-box').offset().left - $('.small-box').find('span').width()/2,
                        top = disy - $('.small-box').offset().top - $('.small-box').find('span').height()/2 + $(window).scrollTop()
                        _this.zoom(left,top)
                })
            }
            appear () {
                $('.small-box').hover(()=>{
                    this.move()
                    $('.small-box').find('span').css('display','block')
                    $('.big-box').css('display','block')
                },()=>{
                    $('.small-box').find('span').css('display','none')
                    $('.big-box').css('display','none')
                })
            }
            wrapappera () {
                $('.share-wrap .share').hover(() =>{
                    $('.share-wrap .share-content').css('display','block')
                },() =>{
                    $('.share-wrap .share-content').css('display','none')
                })
                $('.share-wrap .share-content').hover(() =>{
                    $('.share-wrap .share-content').css('display','block')
                },() =>{
                    $('.share-wrap .share-content').css('display','none')
                })
            }
            fly (e) {
                // console.log(this.detail)/
                if(this.detail){
                    $(`<img src=${this.detail.image} style="display:block;width:30px;height:30px;border-radius:50%">`).fly({
                        start:{
                          left: e.clientX,  //开始位置（必填）#fly元素会被设置成position: fixed
                          top: e.clientY,  //开始位置（必填）
                        },
                        end:{
                          left: $('.a-car').offset().left, //结束位置（必填）
                          top: $('.a-car').offset().top - $(window).scrollTop(),  //结束位置（必填）
                        },
                        speed: 0.8, //越大越快，默认1.2
                        onEnd: function(){
                            this.destroy()
                            header.changeNum()
                        } //结束回调
                      });
                }else{
                    $(`<img src=${this.product.image} style="display:block;width:30px;height:30px;border-radius:50%">`).fly({
                        start:{
                          left: e.clientX,  //开始位置（必填）#fly元素会被设置成position: fixed
                          top: e.clientY,  //开始位置（必填）
                        },
                        end:{
                          left: $('.a-car').offset().left, //结束位置（必填）
                          top: $('.a-car').offset().top - $(window).scrollTop(),  //结束位置（必填）
                        },
                        speed: 0.8, //越大越快，默认1.2
                        onEnd: function(){
                            this.destroy()
                            header.changeNum()
                        } //结束回调
                      });
                }
                
            }
            changePic () {
                var lastindex = 0
                var index = 0
                $('.detail-thumbnail li').on('click',function (){
                    $('.detail-thumbnail li').each( (i,item) =>{
                        $(item).removeClass('ac')
                    })
                    $(this).toggleClass('ac')
                    url = $(this).find('img').attr('src')
                    $('.small-box').find('img').attr('src',url)
                    $('.big-box').find('img').attr('src',url)
                })
            }

        }
        new ShopList()
    })
})